using System;
using ZFramework;

namespace PaintAWorld
{
    public struct ItemSlot
    {
        public int? ItemId { get; private set; }
        public uint Count { get; private set; }

        public readonly bool IsEmpty => Count == 0 || ItemId == null;

        public void Use(Player player)
        {
            if (ItemId is int id)
            {
                ItemProtoDB.Instance.GetEntry(id).Use(this, player);
            }
        }

        public void Drop()
        {
            
        }

        public void StackTo(ItemSlot target, uint count)
        {
            if (ItemId == null || (!target.IsEmpty && target.ItemId != ItemId)) return;

            var maxStackSize = ItemProtoDB.Instance.GetMaxstackSize(ItemId.Value).Value;

            var transferCount = Math.Min(Math.Min(Count, count), maxStackSize - target.Count);
            target.Count += transferCount;
            Count -= transferCount;
        }

        public ItemSlot Split(uint count)
        {
            try
            {
                checked
                {
                    Count -= count;
                }
            }
            catch (OverflowException)
            {
                var resultCount = Count;
                Count = 0;
                return new ItemSlot
                {
                    ItemId = ItemId,
                    Count = resultCount,
                };
            }

            return new ItemSlot
            {
                ItemId = ItemId,
                Count = count,
            };
        }
    }
}